import React, { useCallback, useEffect, useState, useRef, useContext } from 'react'
import { Modal, Row, Col, Button, Dropdown, Space, Select, Checkbox, Cascader, Input, Table, Form } from 'antd';
import DirectoryTreeSelect from "./DirectoryTreeSelect";

import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import type { DefaultOptionType } from 'antd/es/cascader';
import type { InputRef } from 'antd';
import './index.less'


interface DataType {
  key: React.Key;
  name: string;
  value: string;
}

interface Item {
  key: string;
  name: string;
  value: string;
}

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: keyof Item;
  record: Item;
  handleSave: (record: Item) => void;
}

type JumpItemType = {
  type?: number;
  name?: string;
  custom?: boolean;
  id?: number;
  config?: any;
}

const AnalysisTemplate = ({config, onchange}) => {
  // console.log(config)
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );
  return <div style={{padding: '20px'}}>
    <Row>
      <Col span={4} style={{lineHeight: '32px'}}>跳转到:</Col>
      <Col span={20}>
        {/*<Select style={{width: '100%'}}/>*/}
        <DirectoryTreeSelect/>
      </Col>
    </Row>
    <div style={{display: 'flex', justifyContent: 'space-between', margin: '10px 0'}}>
      <div><Checkbox
        checked={config.defineChecked}
        onChange={(e) => {
          onchange({defineChecked: e.target.checked})
          console.log(e.target.checked)
        }}>自定义</Checkbox></div>
      <div><PlusOutlined style={{padding: '4px', color: '#4ec886'}}/>添加</div>
    </div>
    {config.defineChecked ? <Row gutter={10}>
      <Col span={12}>
        <div style={{backgroundColor: '#edf9f2', padding: '5px'}}>源字段</div>
        <Select placeholder={'请选择字段类型'} style={{width: '100%', margin: '10px 0'}}/>
        <Select placeholder={'请选择源字段'} style={{width: '100%'}}/>
      </Col>
      <Col span={12}>
        <div style={{backgroundColor: '#e8f9fe', padding: '5px'}}>目标字段</div>
        {/*<Select style={{width: '100%', margin: '10px 0'}}/>*/}
        <Cascader
          options={[]}
          style={{width: '100%', margin: '10px 0'}}
          onChange={() => {
          }}
          placeholder="请选中目标字段"
          showSearch={{filter}}
          onSearch={(value) => console.log(value)}
        />
        {/*<Select style={{width: '100%'}}/>*/}
      </Col>
    </Row> : null}
  </div>
}


const EditableCell: React.FC<EditableCellProps> = ({
                                                     editable,
                                                     children,
                                                     dataIndex,
                                                     record,
                                                     handleSave,
                                                     ...restProps
                                                   }) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<InputRef>(null);
  
  useEffect(() => {
    if (editing) {
      inputRef.current!.focus();
    }
  }, [editing]);
  
  const toggleEdit = () => {
    setEditing(!editing);
    // form.setFieldsValue({[dataIndex]: record[dataIndex]});
  };
  
  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Input ref={inputRef} defaultValue={record[dataIndex]} onChange={(e) => {
        handleSave({...record, [dataIndex]: e.target.value});
      }} onBlur={toggleEdit}/>
    ) : (
      <div className="editable-cell-value-wrap" style={{paddingRight: 24, height: '24px'}} onClick={toggleEdit}>
        {record[dataIndex]}
      </div>
    );
  }
  
  return <td {...restProps}>{childNode}</td>;
};


const WebUrl = ({config, onchange}) => {
  let initQureyList = (config.jumpUrl||'').split('?')[1]
  if (initQureyList) {
    initQureyList = initQureyList.split('&').map((item: string) => item.split('=')).map((item: any, i: number) => ({key: `${i}`, name: item[0] || '', value: item[1] || ''}))
    initQureyList.push({key: `${initQureyList.length}`, name: '', value: ''})
  } else {
    initQureyList = [{key: `0`, name: '', value: ''}]
  }
  
  
  const [urlValue, setUrlValue] = useState(config.jumpUrl || '');
  const [queryList, setQueryList] = useState<DataType[]>(initQureyList);
  const [count, setCount] = useState(initQureyList.length - 1);
  
  useEffect(() => {
    onchange({jumpUrl: urlValue})
  }, [urlValue]);
  
  const inputChange = (e) => {
    const val = e.target.value
    setUrlValue(val)
    console.log(e.target.value)
    let list = val.split('?')[1]
    if (list) {
      list = list.split('&').map((item: string) => item.split('=')).map((item: any, i: number) => ({key: `${i}`, name: item[0] || '', value: item[1] || ''}))
      setCount(list.length)
      list.push({key: `${list.length}`, name: '', value: ''})
    } else {
      list = [{key: `0`, name: '', value: ''}]
    }
    setQueryList(list)
    
    
  }
  const handleSave = (row: DataType) => {
    console.log('row==', row)
    const newData = [...queryList];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    if (newData[newData.length - 1].name) {
      setCount(pre => pre + 1)
      newData.push({key: `${count + 1}`, name: '', value: ''})
    }
    setQueryList(newData);
    
    setUrlValue(pre => {
      const baseUrl = pre.split('?')[0]
      return `${baseUrl}?${newData.map(item => item.name ? `${item.name}=${item.value}` : null).filter(e => e).join('&')}`
    })
  };
  const defaultColumns = [
    {
      key: '0',
      title: '参数名称',
      dataIndex: 'name',
      width: '30%',
      editable: true,
    },
    {
      key: '1',
      title: '参数值',
      dataIndex: 'value',
      width: '50%'
    },
    {
      key: '2',
      title: '操作',
      width: '20%',
      dataIndex: 'operate',
      render: (_, record) => <Button type={'link'} onClick={() => {
        setQueryList(pre => {
          console.log(pre, count, record)
          const data = pre.filter((item, i) => item.key !== record.key || i === pre.length - 1)
          setUrlValue(pre => {
            const baseUrl = pre.split('?')[0]
            return `${baseUrl}?${data.map(item => item.name ? `${item.name}=${item.value}` : null).filter(e => e).join('&')}`
          })
          return data
        })
      }}>删除</Button>
    },
  ]
  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });
  return <div style={{margin: '0 20px'}}>
    <Input addonBefore="跳转url" value={urlValue} onChange={inputChange}/>
    <Table
      style={{marginTop: '20px'}}
      components={{
        body: {
          // row: EditableRow,
          cell: EditableCell,
        },
      }}
      rowClassName={() => 'editable-row'}
      pagination={false}
      bordered
      scroll={{y: 'auto'}}
      dataSource={queryList}
      columns={columns}
    />
  </div>
  // <Row style={{textAlign: 'center'}} gutter={[0, 10]}>
  //   <Col span={24}>
  //     <Input addonBefore="跳转url" value={urlValue} onChange={inputChange}/>
  //   </Col>
  //   <Col span={24}>
  //     <Table
  //       components={{
  //         body: {
  //           // row: EditableRow,
  //           cell: EditableCell,
  //         },
  //       }}
  //       rowClassName={() => 'editable-row'}
  //       bordered
  //       scroll={{y:500}}
  //       dataSource={queryList}
  //       columns={columns}
  //     />
  //   </Col>
  // </Row>
}

const JumpSet = () => {
  const [jumpModal, setJumpModal] = useState(true);
  const [jumpArr, setJumpArr] = useState<JumpItemType[]>([{
    type: 2,
    name: '网页链接',
    id: Date.now(),
    config: {}
  }]);
  const [selectIndex, setSelectIndex] = useState(0)
  const [jumpItem, setJumpItem] = useState<JumpItemType>({})
  useEffect(() => {
    console.log('selectIndex==', selectIndex)
  }, [selectIndex]);
  
  const items = [{
    label: '分析模板',
    key: '1',
  }, {
    label: '网页链接',
    key: '2',
  }]
  const onClick = ({key}) => {
    if (key === '1') {
      setJumpArr((pre: any) => {
        const item = {
          type: 1,
          name: '分析模板',
          custom: true,
          id: Date.now(),
          config: {}
        }
        return [...pre, item]
      })
    } else {
      setJumpArr((pre: any) => {
        const item = {
          type: 2,
          name: '网页链接',
          id: Date.now(),
          config: {}
        }
        return [...pre, item]
      })
    }
    setSelectIndex(jumpArr.length)
  }
  const onchange = useCallback((config: any) => {
    console.log(config)
    // jumpArr[selectIndex].config = {...jumpArr[selectIndex].config,...config}
    setJumpArr(pre => {
      const data = [...pre]
      console.log('oldPre', data)
      data[selectIndex].config = {...jumpArr[selectIndex].config, ...config}
      console.log('newPre', data)
      return data
    })
  }, [jumpArr, selectIndex])
  
  return <div className={'jumpSet'}>
    <Button onClick={() => setJumpModal(true)}>跳转设置</Button>
    <Modal
      title='跳转设置'
      open={jumpModal}
      width={'50%'}
      // styles={{body:{minHeight:'50vh'}}}
      // bodyStyle={{zIndex: 10000}}
      onOk={() => {
        console.log('ok');
      }}
      onCancel={() => setJumpModal(false)}
    >
      <Row>
        <Col span={6} style={{border: '1px #eee solid', minHeight: '50vh'}}>
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            backgroundColor: '#f2f4f7',
            height: '30px',
            lineHeight: '26px',
            padding: '2px 10px'
          }}>
            <div>添加跳转</div>
            <Dropdown menu={{items, onClick}}>
              <a onClick={(e) => e.preventDefault()}>
                <PlusOutlined style={{padding: '4px', color: '#4ec886'}}/>
              </a>
            </Dropdown>
          </div>
          <div>
            {jumpArr.map((item: any, i: number) => {
              return <div key={i}
                          onClick={() => setSelectIndex(i)}
                          className={'leftList'}
                          style={{
                            // display: 'flex',
                            // justifyContent: 'space-between',
                            backgroundColor: selectIndex === i ? '#f2f4f7' : '#ffffff',
                            // height: '30px',
                            // lineHeight: '26px',
                            // padding: '2px 10px',
                            // marginTop: '5px'
                          }}>
                <span>{item.name}</span>
                <DeleteOutlined className={'del-icon'} onClick={(event) => {
                  console.log(event)
                  event.stopPropagation()
                  if (i < selectIndex) {
                    setSelectIndex(selectIndex > 0 ? selectIndex - 1 : 0)
                  }
                  if (i === selectIndex) {
                    setSelectIndex(selectIndex === jumpArr.length - 1 ? selectIndex - 1 : selectIndex)
                  }
                  setJumpArr(jumpArr.filter((_, index) => i !== index))
                }}/></div>
            })}
          </div>
        
        </Col>
        <Col span={18}>
          {jumpArr[selectIndex] ? <>
            {jumpArr[selectIndex].type === 1 ?
              <AnalysisTemplate
                config={jumpArr[selectIndex].config}
                onchange={onchange}/> :
              <WebUrl
                config={jumpArr[selectIndex].config}
                onchange={onchange}/>}
          </> : null}
        </Col>
      </Row>
    </Modal>
  </div>
}

export default JumpSet;